import { Dropdown, Layout, Menu, MenuProps, Space } from 'antd';

import sty from './styles/index.module.less';
import { useRecoilState } from 'recoil';
import { appStore, appUserStore } from 'src/App.store.ts';
import { Link, useSearchParams } from 'react-router-dom';
import { Navigate, Outlet } from 'react-router';
import qs from 'qs';
import { useCurrentRoute } from 'src/hooks';
type MenuItem = Required<MenuProps>['items'][number];

export function Element() {
  const [state] = useRecoilState(appStore);
  const [user, setUser] = useRecoilState(appUserStore);
  const [search] = useSearchParams();

  const route = useCurrentRoute();

  if (!user) {
    const redirect = search.get('redirect');
    return (
      <Navigate
        to={`/sign-in?${qs.stringify(redirect ? { redirect } : {})}`}
        replace
      />
    );
  }
  return (
    <Layout className={sty.app}>
      <Layout.Header className={sty.header}>
        <Link to="/" className={sty.logo}>
          {state.title}
        </Link>

        <Space>
          <Dropdown.Button
            menu={{
              items: [
                {
                  key: 'LOGOUT',
                  label: '退出',
                  danger: true,
                  onClick: () => setUser(null),
                },
              ],
            }}
            children={user?.name}
          />
        </Space>
      </Layout.Header>

      <Layout hasSider>
        <Layout.Sider theme={state.theme}>
          <Menu
            items={route?.children
              ?.filter((o) => o.path !== '')
              .map(
                (o) =>
                  ({
                    label: o.path,
                    key: o.id,
                    title: o.path,
                  }) as MenuItem,
              )}
          />
        </Layout.Sider>
        '
        <Layout.Content>
          <Outlet />
        </Layout.Content>
      </Layout>
    </Layout>
  );
}

export default Element;
